/**
 * 思维导图工具函数
 * 提供思维导图数据转换、颜色生成等功能
 */

/**
 * 将图谱节点和边转换为思维导图层次结构数据
 * @param {Array} nodes - 图谱节点数组
 * @param {Array} edges - 图谱边数组
 * @returns {Object} 思维导图层次结构数据
 */
export const transformDataForMindMap = (nodes, edges) => {
  if (!nodes || nodes.length === 0) {
    return { name: '空图谱', children: [] };
  }

  // 创建节点映射，便于快速查找
  const nodeMap = {};
  nodes.forEach(node => {
    nodeMap[node.id] = {
      ...node,
      name: node.label || node.name || node.id,
      children: []
    };
  });

  // 找出根节点（入度为0或最小的节点）
  const inDegree = {};
  edges.forEach(edge => {
    const targetId = typeof edge.target === 'object' ? edge.target.id : edge.target;
    inDegree[targetId] = (inDegree[targetId] || 0) + 1;
  });

  // 找出入度为0的节点作为根节点，如果没有，则选择第一个节点
  let rootNode;
  const rootCandidates = nodes.filter(node => !inDegree[node.id]);
  
  if (rootCandidates.length > 0) {
    // 优先选择有出边的节点作为根节点
    const withOutEdges = rootCandidates.filter(node => 
      edges.some(edge => {
        const sourceId = typeof edge.source === 'object' ? edge.source.id : edge.source;
        return sourceId === node.id;
      })
    );
    
    rootNode = withOutEdges.length > 0 ? withOutEdges[0] : rootCandidates[0];
  } else {
    // 如果没有入度为0的节点，选择入度最小的节点
    let minInDegree = Infinity;
    let minInDegreeNode = null;
    
    nodes.forEach(node => {
      const degree = inDegree[node.id] || 0;
      if (degree < minInDegree) {
        minInDegree = degree;
        minInDegreeNode = node;
      }
    });
    
    rootNode = minInDegreeNode || nodes[0];
  }

  // 构建邻接表
  const adjacencyList = {};
  edges.forEach(edge => {
    const sourceId = typeof edge.source === 'object' ? edge.source.id : edge.source;
    const targetId = typeof edge.target === 'object' ? edge.target.id : edge.target;
    
    if (!adjacencyList[sourceId]) {
      adjacencyList[sourceId] = [];
    }
    
    // 添加边的标签信息
    adjacencyList[sourceId].push({
      id: targetId,
      label: edge.label || ''
    });
  });

  // 已访问的节点集合，避免循环引用
  const visited = new Set();
  
  // 递归构建树
  const buildTree = (nodeId, depth = 0) => {
    if (visited.has(nodeId) || depth > 10) { // 防止循环引用和过深的树
      return null;
    }
    
    visited.add(nodeId);
    const node = nodeMap[nodeId];
    
    if (!node) {
      return null;
    }
    
    const children = [];
    
    // 添加子节点
    if (adjacencyList[nodeId]) {
      adjacencyList[nodeId].forEach(child => {
        const childNode = buildTree(child.id, depth + 1);
        if (childNode) {
          // 添加关系标签
          if (child.label) {
            childNode.relationLabel = child.label;
          }
          children.push(childNode);
        }
      });
    }
    
    // 创建新对象，避免修改原始节点
    const result = {
      id: node.id,
      name: node.name,
      type: node.type,
      level: depth,
      data: node
    };
    
    if (children.length > 0) {
      result.children = children;
    }
    
    return result;
  };

  // 从根节点开始构建树
  const rootId = rootNode.id;
  const mindMapData = buildTree(rootId);
  
  return mindMapData || { name: '无法构建思维导图', children: [] };
};

/**
 * 为思维导图生成颜色方案
 * @param {Object} mindMapData - 思维导图数据
 * @param {Array} colorScheme - 颜色方案数组
 * @returns {Array} 颜色数组
 */
export const generateMindMapColors = (mindMapData, colorScheme) => {
  // 默认颜色方案
  const defaultColors = [
    '#52c41a', '#1677ff', '#fa8c16', '#722ed1', 
    '#13c2c2', '#eb2f96', '#f5222d', '#faad14'
  ];
  
  const colors = colorScheme || defaultColors;
  
  // 如果没有数据，返回默认颜色
  if (!mindMapData) {
    return colors;
  }
  
  // 计算最大深度
  const getMaxDepth = (node, depth = 0) => {
    if (!node) return depth;
    
    let maxChildDepth = depth;
    
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => {
        const childDepth = getMaxDepth(child, depth + 1);
        maxChildDepth = Math.max(maxChildDepth, childDepth);
      });
    }
    
    return maxChildDepth;
  };
  
  const maxDepth = getMaxDepth(mindMapData);
  
  // 如果深度大于颜色数量，生成更多的颜色
  if (maxDepth + 1 > colors.length) {
    // 简单复制颜色以满足需求
    const extendedColors = [...colors];
    while (extendedColors.length < maxDepth + 1) {
      extendedColors.push(...colors);
    }
    return extendedColors.slice(0, maxDepth + 1);
  }
  
  return colors;
};

/**
 * 构建思维导图层次结构
 * 这个函数是为了兼容 graphRenderers.js 中的导入
 * @param {Array} nodes - 图谱节点数组
 * @param {Array} edges - 图谱边数组
 * @returns {Object} 思维导图层次结构数据
 */
export const buildMindMapHierarchy = (nodes, edges) => {
  return transformDataForMindMap(nodes, edges);
};

/**
 * 计算思维导图布局
 * @param {Object} hierarchyData - 层次结构数据
 * @param {number} width - 画布宽度
 * @param {number} height - 画布高度
 * @returns {Array} 布局后的节点数组
 */
export const calculateMindMapLayout = (hierarchyData, width, height) => {
  if (!hierarchyData) return [];
  
  const centerX = width / 2;
  const centerY = height / 2;
  
  // 简单的水平树形布局
  const layoutNodes = [];
  const horizontalSpacing = 150;
  const verticalSpacing = 80;
  
  // 递归计算位置
  const calculatePosition = (node, level = 0, index = 0, parentX = centerX, parentY = centerY, side = 'right') => {
    if (!node) return;
    
    // 计算当前节点位置
    let x, y;
    
    if (level === 0) {
      // 根节点放在中心
      x = centerX;
      y = centerY;
    } else {
      // 子节点根据层级和索引计算位置
      const direction = side === 'right' ? 1 : -1;
      x = parentX + direction * horizontalSpacing;
      y = parentY + (index - (node.siblings || 0) / 2) * verticalSpacing;
    }
    
    // 添加到布局节点数组
    layoutNodes.push({
      ...node,
      x,
      y,
      level
    });
    
    // 递归处理子节点
    if (node.children && node.children.length > 0) {
      // 为子节点添加兄弟节点数量信息
      node.children.forEach(child => {
        child.siblings = node.children.length;
      });
      
      // 计算子节点位置
      node.children.forEach((child, i) => {
        // 根节点的子节点左右分布
        let childSide = side;
        if (level === 0) {
          childSide = i % 2 === 0 ? 'right' : 'left';
        }
        
        calculatePosition(child, level + 1, i, x, y, childSide);
      });
    }
  };
  
  // 从根节点开始计算
  calculatePosition(hierarchyData);
  
  return layoutNodes;
};

/**
 * 生成思维导图连接线路径
 * @param {Object} source - 源节点
 * @param {Object} target - 目标节点
 * @returns {string} SVG路径数据
 */
export const generateMindMapPath = (source, target) => {
  if (!source || !target) return '';
  
  const sourceX = source.x || 0;
  const sourceY = source.y || 0;
  const targetX = target.x || 0;
  const targetY = target.y || 0;
  
  // 计算控制点
  const controlX = sourceX + (targetX - sourceX) * 0.5;
  
  // 生成贝塞尔曲线路径
  return `M${sourceX},${sourceY} C${controlX},${sourceY} ${controlX},${targetY} ${targetX},${targetY}`;
};
